<template>
  <view class="history-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-wrapper">
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view v-else-if="historyList.length === 0" class="empty">
      <text class="empty-text">暂无浏览历史</text>
    </view>
    
    <!-- 浏览历史列表 -->
    <view v-else class="history-list">
      <view 
        v-for="item in historyList" 
        :key="item.id"
        class="history-item"
        @click="viewDetail(item)"
      >
        <image 
          :src="item.thumbnail || item.url" 
          mode="aspectFill" 
          class="history-image"
          @error="onImageError"
        />
        <view class="history-info">
          <text class="history-title">{{ item.title || '图片' }}</text>
          <text class="history-time">{{ formatTime(item.viewedAt) }}</text>
        </view>
        <view class="history-actions">
          <view class="action-btn" @click.stop="removeHistory(item.id)">
            <text class="action-icon">🗑️</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading && historyList.length > 0">
      <text class="load-more-text">上拉加载更多</text>
    </view>
    
    <!-- 没有更多 -->
    <view class="no-more" v-if="!hasMore && historyList.length > 0">
      <text class="no-more-text">没有更多了</text>
    </view>
    
    <!-- 清空按钮 -->
    <view class="clear-btn-wrapper" v-if="historyList.length > 0">
      <view class="clear-btn" @click="clearAllHistory">
        <text class="clear-btn-text">清空浏览历史</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app'
import { getViewHistoryList, removeViewHistory, clearViewHistory } from '@/api/history'
import { useImageStore } from '@/stores/image'
import { saveViewHistory } from '@/utils/storage'

const imageStore = useImageStore()
const historyList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const pageSize = ref(20)

onMounted(() => {
  loadHistory()
})

// 加载浏览历史列表
function loadHistory(isRefresh = false) {
  if (loading.value) return
  
  loading.value = true
  
  if (isRefresh) {
    currentPage.value = 1
    historyList.value = []
  }
  
  getViewHistoryList({
    page: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    if (res.code === 200 && res.data) {
      const newList = (res.data.list || []).map(item => ({
        id: item.id,
        title: item.title,
        thumbnail: item.thumbnail || item.url,
        url: item.url,
        width: item.width,
        height: item.height,
        views: item.views || 0,
        likes: item.likes || 0,
        viewedAt: item.viewedAt,
        createTime: item.createTime
      }))
      
      if (isRefresh) {
        historyList.value = newList
      } else {
        historyList.value.push(...newList)
      }
      
      // 同步到 store 和本地存储
      imageStore.viewHistory = historyList.value
      saveViewHistory(historyList.value)
      
      // 判断是否还有更多
      hasMore.value = historyList.value.length < (res.data.total || 0)
      
      if (hasMore.value) {
        currentPage.value++
      }
    }
  }).catch(err => {
    console.error('加载浏览历史失败:', err)
    uni.showToast({
      title: err.message || '加载失败',
      icon: 'none'
    })
  }).finally(() => {
    loading.value = false
  })
}

// 删除浏览历史
function removeHistory(imageId) {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条浏览历史吗？',
    success: (res) => {
      if (res.confirm) {
        removeViewHistory(imageId).then(() => {
          // 从列表中移除
          const index = historyList.value.findIndex(item => item.id === imageId)
          if (index !== -1) {
            historyList.value.splice(index, 1)
            // 同步到 store 和本地存储
            imageStore.viewHistory = historyList.value
            saveViewHistory(historyList.value)
          }
          
          uni.showToast({
            title: '已删除',
            icon: 'success'
          })
        }).catch(err => {
          console.error('删除浏览历史失败:', err)
          uni.showToast({
            title: err.message || '操作失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 清空所有浏览历史
function clearAllHistory() {
  uni.showModal({
    title: '提示',
    content: `确定要清空所有浏览历史吗？共 ${historyList.value.length} 条记录`,
    success: (res) => {
      if (res.confirm) {
        clearViewHistory().then(() => {
          historyList.value = []
          imageStore.viewHistory = []
          saveViewHistory([])
          
          uni.showToast({
            title: '已清空',
            icon: 'success'
          })
        }).catch(err => {
          console.error('清空浏览历史失败:', err)
          uni.showToast({
            title: err.message || '操作失败',
            icon: 'none'
          })
        })
      }
    }
  })
}

// 查看详情
function viewDetail(image) {
  uni.navigateTo({
    url: `/pages/detail/detail?id=${image.id}`
  })
}

// 格式化时间
function formatTime(timeStr) {
  if (!timeStr) return ''
  
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) {
    return '刚刚'
  } else if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    const month = time.getMonth() + 1
    const date = time.getDate()
    return `${month}月${date}日`
  }
}

// 图片加载错误
function onImageError(e) {
  console.error('图片加载失败:', e)
}

// 下拉刷新
onPullDownRefresh(() => {
  loadHistory(true).finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 上拉加载更多
onReachBottom(() => {
  if (hasMore.value && !loading.value) {
    loadHistory()
  }
})
</script>

<style scoped>
.history-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: calc(50px + env(safe-area-inset-bottom)); /* 为 tabbar 留出空间 */
}

.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60vh;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

.history-list {
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.history-item {
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  position: relative;
}

.history-image {
  width: 100%;
  height: 400rpx;
}

.history-info {
  padding: 20rpx;
}

.history-title {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.history-time {
  font-size: 24rpx;
  color: #999;
}

.history-actions {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
}

.action-icon {
  font-size: 32rpx;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.load-more,
.no-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.load-more-text,
.no-more-text {
  font-size: 28rpx;
  color: #999;
}

.clear-btn-wrapper {
  padding: 40rpx 20rpx;
  display: flex;
  justify-content: center;
}

.clear-btn {
  padding: 20rpx 60rpx;
  background-color: #fff;
  border-radius: 50rpx;
  border: 1rpx solid #e0e0e0;
}

.clear-btn-text {
  font-size: 28rpx;
  color: #666;
}
</style>

